#include <QtGui/QApplication>
#include <QSettings>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QDir>
#include <QFileDialog>
#include <QString>

#include "defines.h"
#include "settingswizard.h"
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(qmediacollector);

    QCoreApplication::setOrganizationName("g5network");
    QCoreApplication::setOrganizationDomain("g5network.org");
    QCoreApplication::setApplicationName("QMediaCollector");
    QCoreApplication::setApplicationVersion("0.1.0");

    QApplication a(argc, argv);
    QSettings settings(CONFIG_FILE, QSettings::IniFormat);
    QString dbPath = settings.value("db/path").toString();
    bool loadDb = false;

    if (!QFile::exists(dbPath)) {
        SettingsWizard s;
        if (s.exec()) {
            if (QFile::exists(s.databasePath())) {
                dbPath = s.databasePath();
                loadDb = true;
            } else {
                int ret = QMessageBox::critical(0, a.tr("Cannot open database"),
                                              a.tr("Unable to establish a database connection.\n"
                                                   "\n"
                                                   "Click Cancel to exit."), QMessageBox::Cancel);
                if (ret == QMessageBox::Cancel)
                    return EXIT_FAILURE;
            }
        }
    }
    else
        loadDb = true;

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbPath);
    if (!db.open() || !db.isValid() || !loadDb) {
        int ret = QMessageBox::critical(0, a.tr("Cannot open database"),
                                        a.tr("Unable to establish a database connection.\n"
                                             "\n"
                                             "Click Cancel to exit."), QMessageBox::Cancel);
        if (ret == QMessageBox::Cancel)
            return EXIT_FAILURE;
    }

    MainWindow w;
    w.show();
    
    return a.exec();
}
